package com.pai4j.common.config.annotation;


import com.pai4j.common.enums.RoleCodeEnum;
import com.pai4j.common.exception.AuthException;
import com.pai4j.common.helper.SessionHelper;
import com.pai4j.jianlipai.service.RoleService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 *
 *
 * @author: CYM-pai
 * @date: 2025/10/27 14:50
 **/
public class RequestPermissionInterceptor implements HandlerInterceptor {

    @Resource
    private RoleService roleService;
    
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 取当前Class、method
        Class bean = handlerMethod.getBeanType();
        Method method = handlerMethod.getMethod();
        if (Modifier.PUBLIC != method.getModifiers()) {
            // ValidatePermission 只对public方法生效
            return true;
        }
        // 优先方法级 级 ValidatePermission
        RequestPermission requestPermission = method.getAnnotation(RequestPermission.class);
        if (requestPermission == null) {
            // 方法没有注解，再找找class注解
            requestPermission = (RequestPermission) bean.getAnnotation(RequestPermission.class);
        }
        if (requestPermission == null) {
            return true;
        }

        /***
         * 权限校验
         */
        if (requestPermission.role().length > 0) {
            RoleCodeEnum[] roleEnums = requestPermission.role();
            // 获取当前登录的用户ID
            String userId = SessionHelper.getCurrentUserId();
            if (StringUtils.isBlank(userId)) {
                // 未登录！权限校验失败
                throw new AuthException("未登录！");
            }
            // 一个一个校验，或者的关系：即满足任一权限则通过
            for (RoleCodeEnum roleEnum : roleEnums) {
                // 用户任一权限校验通过，则认为拥有操作权限
                if (roleService.hasRole(userId, roleEnum.getCode())) {
                    return true;
                }
            }
        }
        throw new AuthException("无权限!");
    }
}
